package store.lunangangster.nodeflow.core.component;

import com.alibaba.ttl.TransmittableThreadLocal;
import store.lunangangster.nodeflow.enums.NodeType;
import store.lunangangster.nodeflow.util.KeyGenerator;

/**
 * <h2>次数循环Node</h2>
 * <p>如果业务中需要循环的次数是确定的或是可以计算出的，可以使用该组件
 *
 * @author cwk
 * @version 1.0
 */
public abstract class ForComponent extends NodeComponent {

	private static final ThreadLocal<String> TIMES_KEY_TL = new TransmittableThreadLocal<>();

	/**
	 * 获取一个执行固定次数的LoopComponent
	 */
	public static ForComponent getFixedLoopComponent(int loopTimes) {
		return new ForComponent() {
			@Override
			protected int processLoop() {
				return loopTimes;
			}
		};
	}

	@Override
	public void process() {
		int loopTimes = processLoop();
		String key = KeyGenerator.generate(NodeType.NODE_FOR);
		TIMES_KEY_TL.set(key);
		this.getSlot().setData(key, loopTimes);
	}

	/**
	 * 根据业务返回循环次数
	 * @return 循环次数
	 */
	protected abstract int processLoop();

	@Override
	public String getLoopTimesKey() {
		return TIMES_KEY_TL.get();
	}

	@Override
	public void removeLoopTimesKey() {
		TIMES_KEY_TL.remove();
	}
}
